const app = getApp()

import {
  owner_sequence,
  owner_sequence_list,
  owner_sequence_commit,
  owner_sequence_total,
  get_para,
  video_list,
  property_room_list,
} from '../../api/request'

Page({

  data: {

    type:'01',    //业主接龙

    block_room_code: [{},
      {},
      {},
      {},
      {},
    ],

    room_index_default: [0, 2, 0, 0, 0],

    check_real_mobile: false,
    real_mobile: '', //真实手机号码
    font_size: 'show_size_m', //字号大、中、小
    room_code: '请选择...', //门牌号
    owner_name: '', //业主姓名
    mobile: '', //联系手机
    message: '', //业主留言
    owner_sequence_info: {}, //签名发起信息
    owner_sequence_list: {}, //业主签名列表
    message_length: 0,
    owner_sequence_type: 'submit_date', //排序字段
    owner_sequence_order: 'desc', //排序方式
    signature_num: '1', //签名人数
    record_focus: false, //留言焦点
    prompt: '', //签名处提示
    video_list: {}, //短视频
    autoplay:false,

    cur_video: [], //当前播放视频
    cur_video_index: 0, //当前播放视频位置
    address_street: '', //所在街道 
    fun_list: ['按接龙时间排序', '按门牌号排序', '门牌号不规范业主', '按门牌号查漏'],
    index_sel: 1, //默认选项

    start_point: [0, 0], //开始坐标
  },


  bindMultiPickerColumnChange: function (e) {
    var data = {
      block_room_code: this.data.block_room_code,
      room_index_default: this.data.room_index_default
    };
    data.room_index_default[e.detail.column] = e.detail.value;


    //    console.log(data.room_index_default);
    this.setData(data);
    var m_room_code = ''
    //分期
    if (this.data.block_room_code[0].length > 0) {
      m_room_code = m_room_code + (this.data.room_index_default[0] + 1) + '-'
    }
    console.log(m_room_code)
    //楼栋
    m_room_code = m_room_code + (this.data.room_index_default[1] - 1) + '-'

    //单元
    if (this.data.block_room_code[2].length > 0) {
      m_room_code = m_room_code + (this.data.room_index_default[2] + 1) + '-'
    }

    //楼层
    m_room_code = m_room_code + (this.data.room_index_default[3] + 1) + '-'

    //编号
    m_room_code = m_room_code + (this.data.room_index_default[4] + 1)


    if (this.data.room_index_default[1] == 0 || this.data.room_index_default[1] == 1) {
      m_room_code = this.data.block_room_code[1][this.data.room_index_default[1]] + '-'
    }

    this.setData({
      room_code: m_room_code
    })
  },



  bindPickerChange(e) {
    this.setData({
      index_sel: e.detail.value
    })
    switch (this.data.index_sel) {
      case '0':
        this.setData({
          owner_sequence_type: 'submit_date',
          owner_sequence_order: 'desc', //升序
        })
        break;
      case '1':
        this.setData({
          owner_sequence_type: 'room_code',
          owner_sequence_order: '', //升序
        })
        break;
      case '2':
        this.setData({
          owner_sequence_type: 'room_code_error',
          owner_sequence_order: '', //升序
        })
        break;
      case '3':
        this.setData({
          owner_sequence_type: 'room_code_lost',
          owner_sequence_order: '', //升序
        })
        break;
      default:
        this.setData({
          owner_sequence_type: 'room_code_list', //所有清单
          owner_sequence_order: '', //升序
        })
        break;
    }
    this.owner_sequence_query()
  },

  owner_sequence_query() {
    var data = {
      para: [app.globalData.cur_property_code,
        this.data.owner_sequence_type,
        this.data.owner_sequence_order
      ]
    }
    owner_sequence_list(data).then(res => {
      this.setData({
        owner_sequence_list: res.data,
      })

      //刷新签名人数
      var data = {
        para: [app.globalData.cur_property_code]
      }
      owner_sequence_total(data).then(res => {
        this.setData({
          signature_num: res.data[0].TOTAL
        })
        app.globalData.share_img_url = res.data[0].SHARE_IMG_URL

        //门牌号信息
        var data = {
          para: [app.globalData.cur_property_code]
        }
        property_room_list(data).then(res => {

          var m_block_room_code = this.data.block_room_code
          if (res.data[0].STEP == null) {
            m_block_room_code[0] = []
          } else {
            m_block_room_code[0] = res.data[0].STEP.split(',')
          }

          if (res.data[0].BLOCK == null) {
            m_block_room_code[1] = []
          } else {
            m_block_room_code[1] = res.data[0].BLOCK.split(',')
          }

          if (res.data[0].UNIT == null) {
            m_block_room_code[2] = []
          } else {
            m_block_room_code[2] = res.data[0].UNIT.split(',')
          }

          if (res.data[0].FLOOR == null) {
            m_block_room_code[3] = []
          } else {
            m_block_room_code[3] = res.data[0].FLOOR.split(',')
          }

          if (res.data[0].NO == null) {
            m_block_room_code[4] = []
          } else {
            m_block_room_code[4] = res.data[0].NO.split(',')
          }

          this.setData({
            block_room_code: m_block_room_code
          })
        })

      })
    })
  },

  submit_click() {
    if (this.data.real_mobile == '') {
      //需获取手机号码
      this.setData({
        check_real_mobile: true,
      })
      return;
    }


    if (this.data.room_code.length == 0 || this.data.owner_name.length == 0 || this.data.mobile.length == 0 || this.data.message.length == 0) {
      wx.showModal({
        title: '输入信息不完整',
        showCancel: false,
        content: '请完善小区门牌、业主姓名、手机号、签名留言后重新提交',
      })
      return;
    }

    //敏感词检测      
    wx.cloud.callFunction({
      name: "check_risk_word", //云函数
      data: {
        content: this.data.message
      },
      success: res => {
        console.log('ret=', res)
        var m_errCode = res.result.errCode
        if (m_errCode == '87014') { //敏感词返回代码
          wx.showModal({
            title: '留言提交失败',
            showCancel: false,
            content: '留言信息含有违法违规内容,请检查后重新留言',
          })
          return;
        } else {
          let that = this
          console.log('openid=' + app.globalData.cur_my_openid)
          var data = {
            para: [app.globalData.cur_my_openid, app.globalData.cur_property_code, this.data.room_code, this.data.owner_name, this.data.mobile, this.data.message, this.data.real_mobile]
          }
          owner_sequence_commit(data).then(res => {
            that.owner_sequence_query()
            this.setData({
              record_focus: false, //恢复留言窗口正常显示
            })
            wx.showModal({
              title: '业主签名接龙提交成功',
              showCancel: false,
              content: '你是第【' + res.data[0].RET + '】个业主签名接龙，其它业主还等着呢，请按右上角...将业主签名接龙分享朋友圈或转发小区业主楼栋微信群',
            })
          })

        }
      },
      fail: res => {
        console.log('shibai=', res)
      }

    })
  },

  onLoad: function (options) {
    if (options.cur_property_code) { //研判从分享链接过来
      app.globalData.cur_property_code = options.cur_property_code
      app.globalData.cur_property_name = options.cur_property_name
      app.globalData.cur_my_oenid = options.cur_my_openid
      wx.setStorageSync('switch_code', options.cur_property_code)
      /*
            if (options.from=='friend_circle') {
      //发现从朋友圈转过来 直接进入小程序主页
              wx.switchTab({
                url: '/pages/home/index',
                success(res) {
                  let page = getCurrentPages().pop();
                  if (page == undefined || page == null) {
                    return
                  }
                  page.onLoad(); //重新刷新主页面
                }
              })
            }
      */
    }
    var my_room_code = app.globalData.cur_room_code
    if (my_room_code.indexOf('实名认证') >= 0) {
      my_room_code = ''
    }

    this.setData({
      room_code: my_room_code,
      owner_name: app.globalData.cur_my_name,
      mobile: app.globalData.phoneNumber,
      font_size: wx.getStorageSync('font_size'),
      address_street: app.globalData.cur_street_name,
    })

    var data = {
      para: [app.globalData.cur_property_code,this.data.type],
    }
    owner_sequence(data).then(res => {
      if (res.data.length > 0) {
        this.setData({
          owner_sequence_info: res.data[0],
          message: res.data[0].RECORD_MESSAGE
        })
        this.owner_sequence_query()

        var data = {
          para: [app.globalData.cur_property_code],
        }
        video_list(data).then(res => {
          this.setData({
            video_list: res.data,
            cur_video: res.data[0],
          })
          this.getopenid()
        })

      } else {
        wx.showModal({
          title: '温馨提示',
          showCancel: false,
          content: '【' + app.globalData.cur_property_name + '】小区暂时没有发布业主签名接龙需求',
          success: function (res) {

            var pages = getCurrentPages(); //当前页面
            var beforePage = pages[pages.length - 2]; //前一页
            wx.navigateBack({
              success: function () {
                beforePage.onLoad(); // 执行前一个页面的onLoad方法
              }
            });

          }
        })
      }
    })
  },

  getPhoneNumber: function (e) {
    if (this.data.check_real_mobile) {
      this.submit_click() //提交
      return;
    }

    let _this = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.cloud.callFunction({
        name: 'getMobile',
        data: {
          weRunData: wx.cloud.CloudID(e.detail.cloudID),
        }
      }).then(res => {
        if (this.data.mobile == "") {
          this.setData({
            mobile: res.result.event.weRunData.data.purePhoneNumber,
            real_mobile: res.result.event.weRunData.data.purePhoneNumber,
            check_real_mobile: true,
          })
        } else {
          this.setData({
            real_mobile: res.result.event.weRunData.data.purePhoneNumber,
            check_real_mobile: true,
          })
        }
        this.submit_click() //重新提交

      }).catch(res => {
        console.log('err=', res)
        wx.showModal({
          title: '业主签名接龙需要手机号码授权',
          content: '',
        })
      });

    } else {
      wx.showModal({
        title: '获取手机号码授权失败',
        content: e.detail.errMsg,
      })
    }
  },


  getopenid() {

    var data = {
      para: ['OWNER_SIGNED_PROMPT']
    }
    get_para(data).then(res => {
      var para_value = res.data[0].PARA_VALUE
      this.setData({
        prompt: res.data[0].PARA_VALUE
      })

      const _this = this
      wx.login({
        //获取code 拿openid、sessionKey
        success: (res) => {
          const _this = this
          wx.cloud.callFunction({
            name: "getOpenid", //云函数
            data: {},
            success: res => {
              var openid = res.result.OPENID
              app.globalData.cur_my_openid = openid
              app.globalData.signature_name = ""
            },
            fail(res) {
              console.log("-----get_openid 获取失败-----", res)
            }
          })

        }
      })
    })
  },


  onReady: function () {

  },

  onShow: function () {

  },

  onHide: function () {

  },

  onUnload: function () {

  },

  onPullDownRefresh: function () {

  },

  onReachBottom: function () {},

  onShareAppMessage: function () {

  },

  prompt(e) {
    wx.showModal({
      title: '签名接龙操作提示',
      showCancel: false,
      content: e.target.dataset.prompt,
    })
  },

  //展开更多
  info_more: function (e) {
    var m_owner_sequence_info = this.data.owner_sequence_info
    m_owner_sequence_info.AUTO = 'true'
    m_owner_sequence_info.SEEMORE = 'false'

    this.setData({
      owner_sequence_info: m_owner_sequence_info
    })
  },


  //内容收起
  info_close: function (e) {
    var m_owner_sequence_info = this.data.owner_sequence_info
    m_owner_sequence_info.AUTO = 'true'
    m_owner_sequence_info.SEEMORE = 'true'

    this.setData({
      owner_sequence_info: m_owner_sequence_info
    })
  },

  //输入框聚焦
  onFocus() {
    this.setData({
      record_focus: true
    })
  },

  room_attach_change(e) {
    this.setData({
      room_code: this.data.block_room_code[1][this.data.room_index_default[1]] + '-' + e.detail.value
    })
  },

  field_change(e) {
    var m_room_ctrl_char = '业主' + e.target.dataset.ctrl
    switch (e.target.dataset.field) {
      case "room_code": //0-9删除
        if (e.detail.keyCode >= 48 && e.detail.keyCode <= 57 || e.detail.keyCode == 45 || e.detail.keyCode == 8 || m_room_ctrl_char.indexOf((String.fromCharCode(e.detail.keyCode)).toUpperCase()) >= 0) {
          this.setData({
            room_code: e.detail.value
          })
        } else {
          this.setData({
            room_code: this.data.room_code
          })
        }
        break;
      case "owner_name":
        this.setData({
          owner_name: e.detail.value
        })
        break;
      case "mobile":
        this.setData({
          mobile: e.detail.value
        })
        break;
      case "message":
        this.setData({
          message: e.detail.value,
          message_length: this.data.message.length
        })
        break;
    }
  },

  //字体控制
  font_show(e) {
    var m_size = e.currentTarget.dataset.size;
    this.setData({
      font_size: 'show_size_' + m_size
    })
    wx.setStorageSync('font_size', this.data.font_size)
  },

  // 用户点击右上角分享
  onShareAppMessage: function () {
    return {
      title: app.globalData.signature_name + '已有' + this.data.signature_num + '个业主签名接龙 ' + app.globalData.cur_property_name + this.data.owner_sequence_info.SIGNATURE_TITLE,
      path: '/pages/owner_sequence/index?cur_property_code=' + app.globalData.cur_property_code + '&openid=' + app.globalData.cur_my_openid + '&cur_property_name=' + app.globalData.cur_property_name + '&from=wechar_group',
      imageUrl: app.globalData.share_img_url,
    }
  },

  //分享朋友圈
  onShareTimeline: function () {
    return {
      title: app.globalData.signature_name + '已有' + this.data.signature_num + '个业主签名接龙 ' + app.globalData.cur_property_name + this.data.owner_sequence_info.SIGNATURE_TITLE,
      query: 'cur_property_code=' + app.globalData.cur_property_code + '&openid=' + app.globalData.cur_my_openid + '&cur_property_name=' + app.globalData.cur_property_name + '&from=friend_circle',
      imageUrl: 'https://yz.2alive.cn/image/logo.png',
    }
  },

  touchstartCallback: function (e) {
    this.setData({
      start_point: [e.touches[0].pageX, e.touches[0].pageY]
    })
  },

  touchmoveCallback: function (e) {
    let touch = this.data.touch
    var m_step = 30
    // 单手指缩放移动位置 
    if (e.touches.length == 1) {
      var cur_point = [e.touches[0].pageX, e.touches[0].pageY]
      var start_point = this.data.start_point
      if (cur_point[0] <= start_point[0]) {
        if (Math.abs(cur_point[0] - start_point[0]) >= Math.abs(cur_point[1] - start_point[1])) {
          //left
        } else {
          if (cur_point[1] >= start_point[1]) {
            //down            
            this.video_scroll(-1)
          } else {
            //up
            this.video_scroll(1)
          }
        }
      } else {
        if (Math.abs(cur_point[0] - start_point[0]) >= Math.abs(cur_point[1] - start_point[1])) {
          //right
        } else {
          if (cur_point[1] >= start_point[1]) {
            //down
            this.video_scroll(-1)
          } else {
            //up
            this.video_scroll(1)
          }
        }
      }
      return
    }
  },

  video_scroll(m_id) {
    var m_cur_video_index = this.data.cur_video_index
    m_cur_video_index = m_cur_video_index + m_id
    if (m_cur_video_index > this.data.video_list.length-1) {
      m_cur_video_index = 0
    }
    if (m_cur_video_index < 0) {
      m_cur_video_index = this.data.video_list.length - 1
    }

    var m_cur_video = this.data.video_list[m_cur_video_index]
    this.setData({
      cur_video: m_cur_video,
      cur_video_index: m_cur_video_index,
      autoplay:true,
    })
  },

  douyin_play() {
    wx.setClipboardData({
      data: this.data.cur_video.PASSWORD,
      success: function (res) {
        wx.showModal({
          title: '抖音播放操作提示',
          showCancel: false,
          content: '抖音播放密码已复制，请重新打开抖音APP，看到提示：“业主我当家”的作品，打开看看即可自动播放此抖音内容，也可选择业主微信好友或微信群，粘贴此密码，对方复制后打开抖音即可播放',
        })
      },

      fail: function (res) {
        console.log('shibai', res)
      },
    })
  },
})